package org.spiderdesign.ocr.executor.shape;

import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spiderdesign.ExpressionEngine;
import org.spiderdesign.context.SpiderContext;
import org.spiderdesign.executor.ShapeExecutor;
import org.spiderdesign.model.Shape;
import org.spiderdesign.model.SpiderNode;
import org.spiderdesign.ocr.model.Ocr;
import org.spiderdesign.ocr.service.OcrService;
import org.spiderdesign.ocr.utils.OcrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OcrOperationExecutor implements ShapeExecutor {

    public static final String OCR_ID = "ocrId";

    public static final String BYTES_OR_URL = "bytesOrUrl";

    public static final String VARIABLE_NAME = "variableName";

    private static Logger logger = LoggerFactory.getLogger(OcrOperationExecutor.class);

    @Autowired
    private ExpressionEngine engine;

    @Autowired
    private OcrService ocrService;

    @Override
    public String supportShape() {
        return "ocrOperation";
    }

    @Override
    public Shape shape() {
        Shape shape = new Shape();
        shape.setImage("");
        shape.setLabel("OCR识别");
        shape.setName("ocrOperation");
        shape.setTitle("OCR识别");
        return shape;
    }

    @Override
    public void execute(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
        try {
            int ocrId = NumberUtils.toInt(node.getStringJsonValue(OCR_ID, "0"), 0);
            if (ocrId == 0) {
                logger.debug("请选择OCR！");
            } else {
                Ocr ocr = ocrService.get(ocrId + "");
                String bytesOrUrl = node.getStringJsonValue(BYTES_OR_URL);
                JSONObject jsonResult = null;
                if (bytesOrUrl.startsWith("http")) {
                    jsonResult = OcrUtil.ocrIdentify(ocr, bytesOrUrl);
                } else {
                    byte[] bytes = (byte[]) engine.execute(bytesOrUrl, variables);
                    jsonResult = OcrUtil.ocrIdentify(ocr, bytes);
                }
                if (jsonResult != null) {
                    if (jsonResult.isNull("words_result")) {
                        logger.error(jsonResult.toString());
                    } else {
                        JSONArray wordsResult = jsonResult.getJSONArray("words_result");
                        if (wordsResult != null) {
                            double average = 0;
                            String identifyResult = "";
                            for (int i = 0; i < wordsResult.length(); i++) {
                                JSONObject probability = wordsResult.getJSONObject(i).getJSONObject("probability");
                                if (probability.getDouble("average") > average) {
                                    average = probability.getDouble("average");
                                    identifyResult = wordsResult.getJSONObject(i).getString("words");
                                }
                            }
                            variables.put(node.getStringJsonValue(VARIABLE_NAME), identifyResult);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ocr操作错误：{}", e);
        }
    }

}
